package com.sdp.wx.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.ApplicationContextUtils;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.flow.db.entity.ActHiComment;
import com.sdp.flow.db.service.IWorkflowService;
import com.sdp.flow.dto.FlowParam;
import com.sdp.flow.utils.FlowConstants;
import com.sdp.wx.db.wx_emp.entity.WxEmp;
import com.sdp.wx.db.wx_emp.service.IWxEmpService;
import com.sdp.wx.db.wx_emp_job_transfer.entity.WxEmpJobTransfer;
import com.sdp.wx.db.wx_emp_job_transfer.service.IWxEmpJobTransferService;
import com.sdp.wx.utils.CurrentLoginEmp;
import com.sdp.wx.utils.WxConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-01-26
 */
@RestController
@RequestMapping("/WxEmpJobTransferController")
public class WxEmpJobTransferController {
    @Autowired
    private Query query;
    @Autowired
    private IWxEmpJobTransferService iWxEmpJobTransferService;
    @Autowired
    private CurrentLoginEmp currentLoginEmp;
    @Autowired
    private IWorkflowService workflowService;
    @Autowired
    private IWxEmpService iWxEmpService;
    @PostMapping(value = "/page")
    public Result<?> page(@RequestBody DataCenter dataCenter) {
        return Result.ok(query.page(iWxEmpJobTransferService, WxEmpJobTransfer.class, dataCenter));
    }
    @PostMapping(value = "/save")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> save(@RequestBody WxEmpJobTransfer wxEmpJobTransfer) {
        if(wxEmpJobTransfer==null) {
            return Result.error("个人申请岗位变更信息为空");
        }
        JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
        if(StringUtils.isEmpty(wxEmpJobTransfer.getKeyId())) {
            QueryWrapper<WxEmp> wxEmpQueryWrapper=new QueryWrapper<>();
            wxEmpQueryWrapper.lambda().eq(WxEmp::getEmpNo,emp.getString("empNo"));
            WxEmp wxEmp= iWxEmpService.getOne(wxEmpQueryWrapper,false);
            if(wxEmp == null){
                return Result.error("职工不存在");
            }
            wxEmpJobTransfer.setTransferType(WxConstants.个人申请.getCode());
            wxEmpJobTransfer.setOrgNo(wxEmp.getOrgNo());
            wxEmpJobTransfer.setEmpNo(wxEmp.getEmpNo());
            wxEmpJobTransfer.setEmpGw(wxEmp.getEmpGw());
            wxEmpJobTransfer.setEmpName(wxEmp.getEmpName());
            wxEmpJobTransfer.setCreateTime(LocalDateTime.now());
            wxEmpJobTransfer.setIsFinish(WxConstants.否.getCode());
            wxEmpJobTransfer.setApprovalState(WxConstants.流程审批状态_未提交.getCode());
            wxEmpJobTransfer.setApplicationEmpNo(emp.getString("empNo"));
            wxEmpJobTransfer.setApplicationEmpName(emp.getString("empName"));
            iWxEmpJobTransferService.save(wxEmpJobTransfer);
        }else {
            iWxEmpJobTransferService.updateById(wxEmpJobTransfer);
        }
        return Result.ok();
    }

    /**
     * 领导职位调拨，直接进行变更
     * @param wxEmpJobTransfer
     * @return
     */
    @PostMapping(value = "/saveLeader")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> saveLeader(@RequestBody WxEmpJobTransfer wxEmpJobTransfer) {
        if(wxEmpJobTransfer==null) {
            return Result.error("岗位调拨变更信息为空");
        }
        if(StringUtils.isEmpty(wxEmpJobTransfer.getKeyId())){
            // 添加变更记录
            JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
            wxEmpJobTransfer.setTransferType(WxConstants.领导调拨.getCode());
            wxEmpJobTransfer.setCreateTime(LocalDateTime.now());
            wxEmpJobTransfer.setIsFinish(WxConstants.是.getCode());
            wxEmpJobTransfer.setApplicationEmpNo(emp.getString("empNo"));
            wxEmpJobTransfer.setApplicationEmpName(emp.getString("empName"));
            iWxEmpJobTransferService.save(wxEmpJobTransfer);
            // 修改信息
            QueryWrapper<WxEmp> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(WxEmp::getEmpNo,wxEmpJobTransfer.getEmpNo());
            WxEmp wxEmp= iWxEmpService.getOne(queryWrapper,false);
            if(wxEmp == null){
                return Result.error("人员信息不存在");
            }
            wxEmp.setEmpGw(wxEmpJobTransfer.getTransferGw());
            wxEmp.setOrgNo(wxEmpJobTransfer.getTransferOrgNo());
            iWxEmpService.updateById(wxEmp);
        }else{
            iWxEmpJobTransferService.updateById(wxEmpJobTransfer);
            // 修改信息
            QueryWrapper<WxEmp> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(WxEmp::getEmpNo,wxEmpJobTransfer.getEmpNo());
            WxEmp wxEmp= iWxEmpService.getOne(queryWrapper,false);
            if(wxEmp == null){
                return Result.error("人员信息不存在");
            }
            wxEmp.setEmpGw(wxEmpJobTransfer.getTransferGw());
            wxEmp.setOrgNo(wxEmpJobTransfer.getTransferOrgNo());
            iWxEmpService.updateById(wxEmp);
        }

        return Result.ok();
    }

    @PostMapping(value = "/saveAndStartFlow")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> saveAndStartFlow(@RequestBody WxEmpJobTransfer wxEmpJobTransfer) {
        if(wxEmpJobTransfer==null) {
            return Result.error("个人申请岗位变更为空");
        }
        Result<?> r = ApplicationContextUtils.getBean(WxEmpJobTransferController.class).save(wxEmpJobTransfer);
        if(r==null || !r.isSuccess()) {
            return r;
        }
        JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
        wxEmpJobTransfer.setTemplateId(WxConstants.个人申请职位变动流程模版.getCode());
        //设置审批状态
        wxEmpJobTransfer.setApprovalState(WxConstants.流程审批状态_审批中.getCode());

        //发起流程
        FlowParam flowParam = new FlowParam();
        flowParam.setUserId(emp.getString("empNo"));
        flowParam.setTemplateId(wxEmpJobTransfer.getTemplateId());
        flowParam.setBizId(wxEmpJobTransfer.getKeyId());

        //指定审批人
        Map<String, Object> variableMap = new HashMap<>();
        BusinessContext businessContext = new BusinessContext();
        businessContext.put(WxEmpJobTransfer.class, wxEmpJobTransfer);
        variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, wxEmpJobTransfer.getApprover());
        variableMap.put(WxConstants.流程监听器中执行的类.getCode(), "com.sdp.wx.controller.WxEmpEntryController");
        variableMap.put(WxConstants.流程监听器中执行类的方法.getCode(), "flowCommitListener");
        variableMap.put(WxConstants.流程监听器中执行类的方法的参数.getCode(), businessContext);
        flowParam.setVariableMap(variableMap);
        String instanceId = workflowService.startFlowAndCommit(flowParam);
        if (StringUtils.isEmpty(instanceId)) {
            return Result.error("流程启动失败!");
        }
        //发起成功设置流程实例Id
        wxEmpJobTransfer.setInstanceId(instanceId);
        iWxEmpJobTransferService.updateById(wxEmpJobTransfer);
        return Result.ok(wxEmpJobTransfer);
    }
    /**
     * 流程提交
     * @param wxEmpJobTransfer
     * @return
     */
    @PostMapping(value = "/commit")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> commit(@RequestBody WxEmpJobTransfer wxEmpJobTransfer) {
        if(wxEmpJobTransfer == null) {
            return Result.error("个人申请岗位变更为空");
        }
        if (StringUtils.isEmpty(wxEmpJobTransfer.getKeyId())) {
            return Result.error("个人申请岗位变更内码为空");
        }

        JSONObject emp = currentLoginEmp.getCurrentEmpInfo();
        //提交流程
        if (StringUtils.isEmpty(wxEmpJobTransfer.getTaskId())) {
            return Result.error("入职申请审批信息不完整");
        }
        FlowParam flowParam = new FlowParam();
        flowParam.setUserId(emp.getString("empNo"));

        flowParam.setTaskId(wxEmpJobTransfer.getTaskId());
        if (!StringUtils.isEmpty(wxEmpJobTransfer.getIsPass())) {
            Map<String, Object> variableMap = new HashMap<>();
            variableMap.put("isPass", wxEmpJobTransfer.getIsPass());
            variableMap.put("link", wxEmpJobTransfer.getLink());
            variableMap.put("userName", emp.getString("empName"));
            variableMap.put("userAvatar", emp.getString("profilePicture"));
            variableMap.put("userSign", emp.getString("nameSign"));
            BusinessContext businessContext = new BusinessContext();
            businessContext.put(WxEmpJobTransfer.class, wxEmpJobTransfer);

            String currentNode = workflowService.getCurrentNode(wxEmpJobTransfer.getTaskId());
            if((WxConstants.是.getCode().equals(wxEmpJobTransfer.getIsPass())
                    && ( WxConstants.个人申请职位变动_最后厂领导审批.getCode().equals(currentNode))||(FlowConstants.flow_end_value.equals(wxEmpJobTransfer.getLink())))) {
                //如果节信息是结束
                //或者最后一个环节，没有环节信息，并且是同意通过
                variableMap.put(WxConstants.流程监听器中执行的类.getCode(), "com.sdp.wx.controller.WxEmpJobTransferController");
                variableMap.put(WxConstants.流程监听器中执行类的方法.getCode(), "flowEndListener");
            }else {
                variableMap.put(WxConstants.流程监听器中执行的类.getCode(), "com.sdp.wx.controller.WxEmpJobTransferController");
                variableMap.put(WxConstants.流程监听器中执行类的方法.getCode(), "flowCommitListener");
            }
            variableMap.put(WxConstants.流程监听器中执行类的方法的参数.getCode(), businessContext);


            if (WxConstants.否.getCode().equals(wxEmpJobTransfer.getIsPass())) {
                variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, wxEmpJobTransfer.getApplicationEmpNo());
                if(StringUtils.isEmpty(wxEmpJobTransfer.getApprovalOpinion())){
                    wxEmpJobTransfer.setApprovalOpinion("不同意");
                }
                wxEmpJobTransfer.setApprovalState(WxConstants.流程审批状态_驳回.getCode());
            }else {
                if(StringUtils.isEmpty(wxEmpJobTransfer.getApprovalOpinion()) && !WxConstants.个人申请职位变动_信息填报申请节点.getCode().equals(currentNode)){
                    wxEmpJobTransfer.setApprovalOpinion("同意");
                }
                variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, wxEmpJobTransfer.getApprover());
                wxEmpJobTransfer.setApprovalState(WxConstants.流程审批状态_审批中.getCode());
            }

            flowParam.setVariableMap(variableMap);

            //更新审批人列表
            if(!WxConstants.个人申请职位变动_信息填报申请节点.getCode().equals(currentNode)){
                wxEmpJobTransfer.setApproversList((wxEmpJobTransfer.getApproversList()==null?"":wxEmpJobTransfer.getApproversList())+("["+emp.getString("empNo")+"]"));
            }
        }
        if (!StringUtils.isEmpty(wxEmpJobTransfer.getApprovalOpinion())) {
            flowParam.setOpinion(wxEmpJobTransfer.getApprovalOpinion());
        }
        iWxEmpJobTransferService.updateById(wxEmpJobTransfer);
        workflowService.commitTask(flowParam);
        return Result.ok();
    }
    /**
     * 审批结束后，更改审批状态
     * @param businessContext
     */
    @Transactional(rollbackFor=Exception.class)
    public void flowEndListener(BusinessContext businessContext) throws NoSuchAlgorithmException {
        WxEmpJobTransfer wxEmpJobTransfer = businessContext.get(WxEmpJobTransfer.class);
        if(wxEmpJobTransfer!=null && WxConstants.是.getCode().equals(wxEmpJobTransfer.getIsPass())) {
            wxEmpJobTransfer.setApprovalState(WxConstants.流程审批状态_审批通过.getCode());
            iWxEmpJobTransferService.updateById(wxEmpJobTransfer);
        }
        // 审批全部通过，修改人员岗位信息
        QueryWrapper<WxEmp> wxEmpQueryWrapper=new QueryWrapper<>();
        wxEmpQueryWrapper.lambda().eq(WxEmp::getEmpNo,wxEmpJobTransfer.getEmpNo());
        WxEmp wxEmp= iWxEmpService.getOne(wxEmpQueryWrapper,false);
        wxEmp.setOrgNo(wxEmpJobTransfer.getTransferOrgNo());
        wxEmp.setEmpGw(wxEmpJobTransfer.getTransferGw());
        iWxEmpService.updateById(wxEmp);

    }
    public void flowCommitListener(BusinessContext businessContext) {

    }

    @RequestMapping(value="/queryByInstanceId")
    public Result<?> queryByInstanceId(@RequestParam String instanceId) {
        if (StringUtils.isEmpty(instanceId)) {
            return Result.error("instanceId不能为空!");
        }
        QueryWrapper<WxEmpJobTransfer> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WxEmpJobTransfer::getInstanceId, instanceId);
        WxEmpJobTransfer wxEmpJobTransfer = iWxEmpJobTransferService.getOne(queryWrapper, false);
        List<ActHiComment> commentList = workflowService.getApprovedOpinionNew(instanceId);
        wxEmpJobTransfer.setApprovalOpinions(commentList);
        return Result.ok(wxEmpJobTransfer);
    }
    /**
     * 流程撤销
     * @param instanceId
     * @return
     */
    @GetMapping(value = "/cancel")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> cancel(@RequestParam(name="instanceId",required=true) String instanceId) {
        LambdaQueryWrapper<WxEmpJobTransfer> query = new LambdaQueryWrapper<>();
        query.eq(WxEmpJobTransfer::getInstanceId, instanceId);
        WxEmpJobTransfer wxEmpJobTransfer = iWxEmpJobTransferService.getOne(query);
        if(wxEmpJobTransfer==null) {
            return Result.error("员工离职信息不存在，不能进行撤销");
        }
        JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
        if(!wxEmpJobTransfer.getApplicationEmpNo().equals(emp.getString("empNo"))) {
            return Result.error("不是提交人，不能进行撤销操作");
        }
        //流程撤销
        workflowService.stopFlow(instanceId, "撤销");
        //删除个人申请岗位变更申请信息
        iWxEmpJobTransferService.removeById(wxEmpJobTransfer.getKeyId());
        return Result.ok();
    }

}

